package com.hebtu.helper.modules.sys.service.impl;


import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.hebtu.helper.common.utils.H;
import com.hebtu.helper.modules.sys.service.SysMenuService;
import com.hebtu.helper.modules.sys.service.SysRoleMenuService;
import com.hebtu.helper.modules.sys.service.SysUserRoleService;
import com.hebtu.helper.modules.sys.dao.SysMenuDao;
import com.hebtu.helper.modules.sys.entity.SysMenuEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service("sysMenuService")
public class SysMenuServiceImpl extends ServiceImpl<SysMenuDao, SysMenuEntity> implements SysMenuService {

    @Autowired
    private SysUserRoleService sysUserRoleService;
    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 根据userId查询菜单
     * 1、查询改用户的所有角色
     * 2、查询角色对应的菜单id
     * 3、根据菜单id查询所有菜单实体
     * @param userId 用户id
     * @return
     */
    @Override
    public List<SysMenuEntity> list(Long userId) {
        List<Long> roles=sysUserRoleService.queryRolesByUserID(userId);
        //是否是管理员
        if(roles.get(0)==1){
            return baseMapper.selectList(null);
        }
        if(roles.size()==0)
            return null;
        List<Long> menuIds=sysRoleMenuService.queryMenuIdByRoleId(roles);
        if (menuIds.size()==0) {
            return null;
        }
        List<SysMenuEntity> sysMenuEntities = new ArrayList<>();
        for (Long menuId : menuIds) {
            sysMenuEntities.add(baseMapper.selectById(menuId));
        }
        return sysMenuEntities;
    }

    @Override
    public H delete(Long menuId) {
        List<SysMenuEntity> childMenu=queryAllChildByMenuId(menuId);
        if (childMenu != null)
            if(childMenu.size()!=0)
                return H.error("请先删除所有子菜单");

       return baseMapper.deleteById(menuId)!=0?H.success("删除成功"):H.error(203,"删除失败");
    }

    /**
     * 根据menuId查询所有子菜单
     * @param menuId
     */
    @Override
    public List<SysMenuEntity> queryAllChildByMenuId(Long menuId) {
        SysMenuEntity sysMenuEntity=baseMapper.selectById(menuId);

        if (sysMenuEntity.getParentId() ==0) {
            //父级菜单
            Map<String, Object> map = new HashMap<>();
            map.put("parent_id", menuId);
            return baseMapper.selectByMap(map);
        }
        return null;
    }

}
